package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TextView;

import com.ruike.alisurface.MyApplication;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.ICCardUtils;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.CardCreateOrderByProductBean;
import com.ruike.alisurface.bean.CardCreateOrderBySlotBean;
import com.ruike.alisurface.bean.CardInfoBean;
import com.ruike.alisurface.bean.CardOrderBean;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.http.CardHttp;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.utils.MyCountDownTimer;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.TimeUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class PayCardActivity extends BaseAty implements ICCardUtils.OnICCardGetPwdListener {

    @BindView(R.id.payCard_operationTips_tv)
    TextView operationTipsTv;
    @BindView(R.id.payCard_payInfo_tabLayout)
    TableLayout payInfoTabLayout;
    @BindView(R.id.payCard_cardNumber_tv)
    TextView cardNumberTv;
    @BindView(R.id.payCard_payPrice_tv)
    TextView payPriceTv;
    @BindView(R.id.payCard_yemoney_tv)
    TextView yemoneyTv;
    @BindView(R.id.payCard_payTime_tv)
    TextView payTimeTv;
    @BindView(R.id.payCard_countTime_tv)
    TextView countTimeTv;

    List<CarGoodsBeans> paycarlist;//商品 数据
    double monry = 0.0f;
    String cardNum; // 刷卡的卡号
    String cardPwd; // 读取的卡密码

    private boolean isCardRequest = true; // 获取到卡号之后是否需要请求

    @Override
    protected boolean getCanToOtherApp() {
        return false;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_pay_card;
    }

    @Override
    protected void initViews() {
        startCountdownTimer(120, countTimeTv, SelectPayTypeActivity.class);
        initTitleBar(false);
    }

    @Override
    protected void initData() {
        ICCardUtils.setOnICCardGetPwdListener(this);

        // 计算购物车商品的总金额并展示在界面上
        paycarlist = MyApplication.finalDbUtils.findAll(CarGoodsBeans.class);
        if (paycarlist == null || paycarlist.size() <= 0) {
            return;
        }
        for (CarGoodsBeans carGoodsBean : paycarlist) {
            if (carGoodsBean != null && carGoodsBean.getPrice() > 0) {
                monry += carGoodsBean.getPrice();
            }
        }
        payPriceTv.setText(new StringBuffer("¥").append(monry));
    }

    @Override
    protected void onResume() {
        super.onResume();
        ICCardUtils.getCardPwd(120_000); // 开始获取卡块区的内容
    }

    @OnClick({R.id.payCard_goback_imgv})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.payCard_goback_imgv:
                startActivity(SelectPayTypeActivity.class, null);
                finish();
                break;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        // 串口发送的EventBus消息接收
    }

    @Override
    protected void onPause() {
        super.onPause();
        ICCardUtils.stopGetCard();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 读取块区回调
     *
     * @param cardBlocksData 解析出来之后的数据
     */
    @Override
    public void onResultCardPwd(String cardBlocksData) {
        // 第一次回调需要请求详情，防止一直回调一直请求
        if (isCardRequest) {
            isCardRequest = false;
            this.cardPwd = ""; // 先清空一下卡密码
            this.cardPwd = cardBlocksData.toLowerCase(); // 获取到卡密码回调，将密码保存到成员变量中，后台要把获取到的密码转换成小写
            showProgressDialog("正在获取卡信息，请稍后...", false);
            CardHttp.getCardDetails(cardBlocksData, this); // 请求后台查询卡信息
        }
    }

    /**
     * 刷卡异常
     *
     * @param errorMsg 异常信息
     */
    @Override
    public void onCreditCardError(String errorMsg) {
        showErrorTip(errorMsg);
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("card/get_card_details")) { // 查询到卡信息
            CardInfoBean cardInfoBean = GsonUtils.json2Model(requestJsonStr, CardInfoBean.class);
            cardNum = cardInfoBean.getData().getCard_no(); // 回传的卡号放到成员变量中
            cardNumberTv.setText(cardNum);
            yemoneyTv.setText(String.valueOf(cardInfoBean.getData().getNow_balance()));
            if (cardInfoBean.getData().getNow_balance() > monry) {
                operationTipsTv.setVisibility(View.GONE); // 隐藏刷卡提示
                payInfoTabLayout.setVisibility(View.VISIBLE); // 展示开信息的提示
                String currentTimeStr = TimeUtils.millis2String(System.currentTimeMillis());
                payTimeTv.setText(currentTimeStr);

                if (ShareUtils.getInstance().getInt(ShareKey.IS_SHOP_TYPE, 1) == 1) {
                    L.i("按货道展示下单");
                    createOrderBySlot();
                } else {
                    L.i("按商品类型展示下单");
                    createOrderByProduct();
                }
            } else {
                showErrorTip("卡余额不足，不能完成支付，请先进行充值...");
            }
            return;
        }
        if (requestUrl.endsWith("Rk_Card_CreateOrder_BySlot") || requestUrl.endsWith("Rk_Card_CreateOrder_ByProduct")) { // 按照货道下单返回 或者 按照商品下单返回
            // 暂停两秒钟再去处理，免得网络太流畅（虽然很多时候网很渣）的时候展示的信息一闪而过
            new MyCountDownTimer(2000, 2000) {

                @Override
                public void onTick(long millisUntilFinished) {
                }

                @Override
                public void onFinish() {
                    // 无论按照商品下单还是按照货道下单，返回的对象都是一样的
                    CardOrderBean cardOrderBean = GsonUtils.json2Model(requestJsonStr, CardOrderBean.class);

                    ShopDetailBean shopDetailBean = new ShopDetailBean(cardOrderBean.getData().getId());
                    shopDetailBean.setTotal_fee(cardOrderBean.getData().getTotal_fee());
                    shopDetailBean.setPay_fee(cardOrderBean.getData().getPay_fee());
                    shopDetailBean.setPromotion_fee(cardOrderBean.getData().getPromotion_fee());
                    shopDetailBean.setDiscount_fee(cardOrderBean.getData().getDiscount_fee());

                    List<ShopDetailBean.OrderDetailsBean> shopOrderDetailsBeanList = new ArrayList<>();
                    shopOrderDetailsBeanList.clear();

                    for (CardOrderBean.DataBean.DetailsBean detailsBean : cardOrderBean.getData().getDetails()) {
                        ShopDetailBean.OrderDetailsBean shopOrderDetailsBean = new ShopDetailBean.OrderDetailsBean();
                        shopOrderDetailsBean.setSlotTypeId(detailsBean.getSlotTypeId()); // 货道类型
                        shopOrderDetailsBean.setSlotIndex(detailsBean.getSlotIndex()); // 出货货道编号
                        shopOrderDetailsBean.setQuantity(detailsBean.getQuantity()); // 出货数量
                        shopOrderDetailsBeanList.add(shopOrderDetailsBean);
                    }

                    shopDetailBean.setDetailOrderList(shopOrderDetailsBeanList);

                    Bundle bundle = new Bundle();
                    bundle.putString("pay_type", "weCard");
                    bundle.putSerializable("orderBeanData", shopDetailBean);
                    startActivity(PayShowShopActivity.class, bundle);
                    finish();
                }
            }.start();
            return;
        }
    }

    @Override
    public void onError(String requestUrl, String requestMsg) {
        super.onError(requestUrl, requestMsg);
        showErrorTip(requestMsg);
        new MyCountDownTimer(1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                isCardRequest = true;
                ICCardUtils.getCardPwd(100_000);
            }
        }.start();
    }

    /**
     * 按照货道下单
     * <p>
     * mchid	是	string	机器ID
     * card_no	是	string	卡号
     * card_pwd	是	string	卡密码
     * details	是	jsonarray	购物详情
     * details—->slotIndex	是	int	货道
     * details—->quantity	是	int	数量
     */
    public void createOrderBySlot() {
        L.i("paycarlist", paycarlist);
        try {

            Map<String, Integer> map = new HashMap<>();
            for (CarGoodsBeans carGoodsBean : paycarlist) {
                String slotIndex = carGoodsBean.getSlotIndexs();
                if (map.containsKey(slotIndex)) {
                    map.put(slotIndex, map.get(slotIndex) + 1);
                } else {
                    map.put(slotIndex, 1);
                }
            }

            List<CardCreateOrderBySlotBean.DetailsBean> detailsBeanList = new ArrayList<>();
            CardCreateOrderBySlotBean.DetailsBean detailsBean;
            for (String key : map.keySet()) {
                detailsBean = new CardCreateOrderBySlotBean.DetailsBean();
                detailsBean.setQuantity(map.get(key)); // 数量
                detailsBean.setSlotIndex(Integer.parseInt(key)); // 货道号
                detailsBeanList.add(detailsBean);
            }

            CardCreateOrderBySlotBean cardCreateOrderBySlotBean = new CardCreateOrderBySlotBean();
            cardCreateOrderBySlotBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            cardCreateOrderBySlotBean.setCard_no(cardNum);
            cardCreateOrderBySlotBean.setCard_pwd(cardPwd);
            cardCreateOrderBySlotBean.setDetails(detailsBeanList);
            L.i("按货道创建的订单对象：" + cardCreateOrderBySlotBean);

            MchApiHttp.cardCreateOrderBySlot(cardCreateOrderBySlotBean, this);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 按照商品类型下单
     */
    public void createOrderByProduct() {
        L.i("paycarlist", paycarlist);
        try {

            if (paycarlist == null || paycarlist.size() <= 0) {
                L.e("订单数据异常：" + paycarlist);
                return;
            }

            List<CardCreateOrderByProductBean.DetailsBean> detailsBeanList = new ArrayList<>();
            CardCreateOrderByProductBean.DetailsBean detailsBean;
            for (CarGoodsBeans cardGoodsBean : paycarlist) {
                detailsBean = new CardCreateOrderByProductBean.DetailsBean();
                detailsBean.setProductid(cardGoodsBean.getProductid());
                detailsBean.setQuantity(1);
                List<Integer> slotIndexList = GsonUtils.jsonArray2ModelList(cardGoodsBean.getSlotIndexs(), Integer.class);
                detailsBean.setSlotIndexs(slotIndexList);
                detailsBeanList.add(detailsBean);
            }

            CardCreateOrderByProductBean cardCreateOrderByProductBean = new CardCreateOrderByProductBean();
            cardCreateOrderByProductBean.setMchid(ShareUtils.getInstance().getString(ShareKey.MCH_ID, ""));
            cardCreateOrderByProductBean.setCard_no(cardNum);
            cardCreateOrderByProductBean.setCard_pwd(cardPwd);
            cardCreateOrderByProductBean.setDetails(detailsBeanList);
            L.i("按商品创建的订单对象：" + cardCreateOrderByProductBean);

            MchApiHttp.cardCreateOrderByProduct(cardCreateOrderByProductBean, this);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
